
import java.util.concurrent.Semaphore;

/**
 * 信号量：实现限流
 */
public class SemaphoreDemo1 {
    public static void main(String[] args) {

        // 创建线程池
//        ExecutorService service = Executors.newFixedThreadPool(10);

        // 创建信号量
        Semaphore semaphore = new Semaphore(1);

        for (int i = 0;i < 10; i++){
//            try {
//                Thread.sleep(500);
//            } catch (InterruptedException exception) {
//                exception.printStackTrace();
//            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Thread currThread = Thread.currentThread(); // 得到执行此任务的线程
                    System.out.println(currThread.getName() + "开始执行");
                    try {
                        // 获取令牌
                        semaphore.acquire(); // 如果没有可用令牌的话，那么线程会阻塞在当前位置
                        System.out.println(currThread.getName() + "：得到了令牌 " );
                        Thread.sleep(500);
                    } catch (InterruptedException exception) {
                        exception.printStackTrace();
                    } finally {

                        // 释放令牌
                        semaphore.release();
                    }
                }
            }, "Thread-" + i).start();

        }
    }
}